package net.aynt.blog.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import net.aynt.core.mvc.WebContext;
//import net.aynt.core.util.web.ImgStorageService;
import net.aynt.core.util.web.Multimedia;
import net.aynt.core.util.web.QiNiuStorageService;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
 
/**
 * Action类常用工具
 * @author Winter Lau @ OSChina
 */
public class HTMLImageFetcher{
    
    /**
     * 下载HTML文档中的所有图片
     * @param html
     * @return
     */
    public static String fetchHTML_Images(String html) {
        if(StringUtils.isBlank(html))
            return html;
        HashMap<String, String> img_urls = new HashMap<String,String>();
        Document doc = Jsoup.parse(html);
        Elements imgs = doc.select("img");
        for(int i=0;i<imgs.size();i++){
            Element img = imgs.get(i);
            String src = img.attr("src");
            if(!src.startsWith("/"))
            try {
                URL imgUrl = new URL(src);
                String imgHost = imgUrl.getHost().toLowerCase();
                if(!imgHost.endsWith(".aynt.net")){
                    String new_src = img_urls.get(src);
                    if(new_src == null){
                        new_src = fetchImageViaHttp(imgUrl);
                        img_urls.put(src, new_src);
                    }
                    img.attr("src", new_src);
                }
            } catch (MalformedURLException e) {
                img.remove();
            } catch (Exception e){
                e.printStackTrace();
                img.remove();
            }
        }
        return doc.body().html();
    }
     
    private static String fetchImageViaHttp(URL imgUrl) throws IOException {
        String sURL = imgUrl.toString();
        String imgFile = imgUrl.getPath();
        HttpURLConnection cnx = (HttpURLConnection)imgUrl.openConnection();
        String uri = null;
//		StorageService ss = StorageService.IMAGE;   存储在项目
//		ImgStorageService ss = ImgStorageService.IMAGE; 存储在自定义域名
		QiNiuStorageService ss = QiNiuStorageService.IMAGE;//存储在七牛
        try{
            cnx.setAllowUserInteraction(false);         
            cnx.setDoOutput(true);
            cnx.addRequestProperty("Cache-Control", "no-cache");
            WebContext ctx = WebContext.get();
            if(ctx != null)
                cnx.addRequestProperty("User-Agent", ctx.getHeader("user-agent"));
            else
                cnx.addRequestProperty("User-Agent", user_agent);
            cnx.addRequestProperty("Referer", sURL.substring(0, sURL.indexOf('/', sURL.indexOf('.'))+1));
            cnx.connect();
            if(cnx.getResponseCode() != HttpURLConnection.HTTP_OK)
                return null;
            InputStream imgData = cnx.getInputStream();
            String ext = FilenameUtils.getExtension(imgFile).toLowerCase();
            if(!Multimedia.isImageFile("aa."+ext))
                ext = "jpg";
			uri = ss.save(imgData,ext);
        }finally{
            cnx.disconnect();
        }
        return ss.getReadPath() + uri;      
    }
    private final static String user_agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)";
     
}